package com.song.common.config.web;

import com.song.common.constant.DatePatternConstant;
import com.song.common.constant.DateRegex;
import com.song.common.util.LocalDateTimeUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

@Component
public class LocalDateConverter implements Converter<String, LocalDate> {
    @Override
    public LocalDate convert(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        }
        if (source.matches(DateRegex.YEAR + "-" + DateRegex.MONTH + "-" + DateRegex.DAY)){
            return LocalDateTimeUtil.stringToLocalDate(source, DatePatternConstant.DEFAULT_SHORT_PATTERN);
        }else if (source.matches(DateRegex.YEAR + "/" + DateRegex.MONTH + "/" + DateRegex.DAY)){
            return LocalDateTimeUtil.stringToLocalDate(source, DatePatternConstant.SHORT_PATTERN);
        }else if (source.matches(DateRegex.YEAR + "." + DateRegex.MONTH + "." + DateRegex.DAY)){
            return LocalDateTimeUtil.stringToLocalDate(source, DatePatternConstant.POINT_SHORT_PATTERN);
        }else {
            throw new IllegalArgumentException("Invalid date value '" + source + "'");
        }
    }
}
